import React, { useState, useEffect } from 'react'
import { Column } from '@ant-design/plots'
import { request } from '../../../api/request'

const GoodsRank: React.FC = () => {
  const [data, setData] = useState([])

  useEffect(() => {
    asyncFetch()
    request.get({ url: '/dashboard/goodsRank' }).then((res) => {
      if (res.data !== null) {
        setData(res.data)
        console.log(res.data)
      }
    })
  }, [])

  const asyncFetch = () => {
    fetch(
      'https://gw.alipayobjects.com/os/antfincdn/PC3daFYjNw/column-data.json'
    )
      .then((response) => response.json())
      .then((json) => {
        // setData(json)
      })
      .catch((error) => {
        console.log('fetch data failed', error)
      })
  }
  const config = {
    data,
    xField: 'city',
    yField: 'total',
    seriesField: 'goods',
    isGroup: 'true',
    legend: {
      position: 'right-top',
      offsetX: 8,
      title: {
        text: '产品类别 (销售量）',
        spacing: 8,
      },
      itemValue: {
        formatter: (text: any, item: any) => {
          const items = data.filter((d: any) => {
            console.log('d', d)
            console.log('item', item)

            return d.goods === item.value
          })
          return items.length
            ? items.reduce((a, b: any) => a + b.total, 0) / items.length
            : '-'
        },
        style: {
          opacity: 0.65,
        },
      },
    },
  } as any

  return <Column {...config} />
}

export default GoodsRank
